<script setup lang="ts">
  import { ref } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { matchSignType } from '@/utils/types'
  import information from '@/components/informationMatch/index.vue'
  import { formValidate, msg, phoneCode, wechatPayment } from '@/utils/tools'
  import { getEventsItemTree, getIsMechanism,
    personalRegistry,
    personOrderInfo,
	creatOrder,
	getOrderPrice
  } from '@/api/match'

  const bottomPadding = (uni.getSystemInfoSync().screenHeight as number) - (uni.getSystemInfoSync().safeArea.bottom as number)
  const eventName = ref('2024四川“选星计划”篮球项目U系列锦标赛')
  const agreeToExplain = ref(false)
  const columnsList = ref([])
  const isMechanism = ref(false)
  const eventsNumberNameSelect = ref('')
  const signFrom = ref<matchSignType>({
	  eventId: 1,
	  height:'',
	  weight:'',
	  eventName:'2024四川“选星计划”篮球项目U系列锦标赛',
	  userId: '',
	  rigGroup:'',
	  eventLevel:'',
	  teamName:'',
	  insCode:'',
	  competeName:'',
	  sex:'',
	  age:'',
	  idCard:'',
	  phone:'',
	  emContact:'',
	  emPhone:'',
	  uniformNumber:'',
	  clothingSize:'',
	  cityName:'',
	  districtName:'',
	  districtCode:'',
	  reUnits:'',
	  rigType:'',
	  cityCode:'',
	  provinceCode: '',
	  eventType: '',
	  provinceName: '',
	  photo: [],
	  insName: '',
	  cityId: ''
  })
  const signFromRule = {
    competeName:{message:'请输入姓名'},
    sex:{message:'请选择性别'},
    idCard:{message:'请输入身份证信息',patternType:'idCard'},
    height:{message:'请输入身高'},
    weight:{message:'请输入体重'},
    // eventType:{message:'请选择赛事类型'},
    age:{message:'请输入年龄'},
    teamName:{message:'请选择球队'},
	eventLevel:{message:'请选择参赛层级'},
	rigGroup:{message:'请选择报名组别'},
    clothingSize:{message:'请选择衣服尺码'},
    uniformNumber:{message:'请输入球衣号码'},
    cityId:{message:'请选择所在城市'},
	rigType:{message:'请选择报名类型'},
    photo:{message:'请输入上传蓝底证件照'},
	phone:{message:'请输入联系方式',patternType:'phone'},
	emContact:{message:'请输入紧急人'},
	emPhone:{message:'请输入紧急联系方式',patternType:'phone'},
  }

	const price = ref()
  onLoad((options:any) => {
	getOrderPrice().then(res => {
		if(res.code == 200){
		   price.value = res.data
		}
	})
	// 暂时写死
    // let params = {
    //   eventName:'2024四川“选星计划”篮球项目U系列锦标赛',
    //   eventId:1, // 赛事id
    //   orderId:'',
    //   mechanism:'',
    //   eventsNumberNameSelect:''
    // }
	
    // if(options.params) {
    //   params = JSON.parse(decodeURIComponent(options.params))
    // }
    // eventName.value = '2024四川“选星计划”篮球项目U系列锦标赛'
    // eventName.value = params.eventName'2024四川“选星计划”篮球项目U系列锦标赛'
    // eventsNumberNameSelect.value = params.eventsNumberNameSelect
    // signFrom.value.eventId = params.eventId

    // if(params.orderId){
    //   getPersionalFrom(params.orderId)
    // }
    // if(params.eventId){
    //   projectChange(params.eventId)
    // }

    // 判断是否机构报名
    // getIsMechanism().then(res => {
    //   if(res.code === 200){
    //     isMechanism.value = res.data
    //   }
    // })

  })

  const getPersionalFrom = (data:any) => {
    personOrderInfo({id:data}).then(res => {
      if(res.code == 200){
        for(let key in signFrom.value){
            signFrom.value[key] = res.data[key]
        }
        if(res.data.eventsItems.length > 0){
          signFrom.value.eventsItemIds = res.data.eventsItems.map((item:any) => {
            return item.id
          })
        }
        signFrom.value.eventsItemIds = signFrom.value.eventsItemIds ? signFrom.value.eventsItemIds : []
        eventName.value = res.data.eventsName + '--' + res.data.itemName
        eventsNumberNameSelect.value = res.data.eventsNumberName
      }
    })
  }
  const agreeChange = (e:any) => {
	  agreeToExplain.value = !agreeToExplain.value
    // if(agreeToExplain.value){
    //   agreeToExplain.value = false
    // }else{
    //   registrationNotice()
    // }
  }
  const formDataInfo = ref({})
  const personalClick = async () => {
    formDataInfo.value = JSON.parse(JSON.stringify(signFrom.value))
	formDataInfo.value.userId = uni.getStorageSync('userInfo')?.aid || ''
	formDataInfo.value.age = Number(signFrom.value.age)
	formDataInfo.value.uniformNumber = Number(signFrom.value.uniformNumber)
	formDataInfo.value.photo = signFrom.value.photo.length == 0 ? '': signFrom.value.photo[0]?.fullUrl
	if (formDataInfo.value.cityId) {
		delete formDataInfo.value.cityId
	}
	if(signFrom.value.teamName1) {
		formDataInfo.value.teamName = signFrom.value.teamName1
	}
	// console.log('报名参数', formDataInfo.value)
    // if(statusEnum == 1) {
    //   if (!agreeToExplain.value) {
    //     msg('请先阅读并同意《报名须知》')
    //     return false
    //   }
    // }
    // if(isMechanism.value){
    //   await formValidate(signFrom.value, signFromRule)
    // }else{
    //   await formValidate(signFrom.value, signFromRuleTwo)
    // }
	await formValidate(signFrom.value, signFromRule)
	
    if(formDataInfo.value.phone && !phoneCode(formDataInfo.value.phone)){
      msg('请输入正确的联系电话',false)
      return false
    }
    if(formDataInfo.value.emPhone && !phoneCode(formDataInfo.value.emPhone)){
      msg('请输入正确的紧急联系方式',false)
      return false
    }
	if (!formDataInfo.value.provinceCode){
		msg('请选择所在城市！',false)
	}
	
	if(formDataInfo.value.provinceCode && formDataInfo.value.provinceCode !== "510000"){
	  msg('请选择四川省省市区！',false)
	  return false
	}
    submitRequest(formDataInfo.value)
  }
  const submitRequest = (data: any) => {
	  // const data = 	{"eventPayPrice": 0.02, "eventRefundPrice": 0.01, "eventId":1,"height":190,"weight":100,"eventName":"2024四川“选星计划”篮球项目U系列锦标赛","userId":"eshimin98598354","rigGroup":"U6 男女混合组（6岁）：出生日期为2018年1月1日—2018年12月31日","eventLevel":"省","teamName":"a球队","insCode":"111","competeName":"张三","sex": 0,"age":12,"idCard":"530424200809221889","phone":"17878777878","emContact":"里斯","emPhone":"18787887878","uniformNumber":21,"clothingSize":"M","cityName":"宜宾市","districtName":"江安县","districtCode":2628,"reUnits":"111","rigType":"领队","cityCode":2506,"provinceCode":3515,"eventType":"篮球比赛","provinceName":"四川省","photo":"https://pro.star.ihehang.com/api/file/download/2024/11/19/1732012394177_nJyix5XOyrEd14c13a272a05966db59e942aeb3116eb.jpg"}
    personalRegistry(data).then(res => {
      if(res.code == 200){
		orderCreat(res.data)
      } else if (res.code == 201) {
		  msg('球衣号重复，请重新填写！')
	  }
    })
  }
  
  const orderCreat = (id: any) => {
	  const params = {
	  	reportId: id, 
	  	openid: uni.getStorageSync('openId'),  
	  	type:"MIN", 
	  	insuranceAmountStr: price.value?.insuranceAmountStr, 
	  	orderAmountStr: price.value?.orderAmountStr, 
	  	payType:1, 
	  	orderRemark:"", 
	  	productType:"GAME"
	  }
	  // const params = {"reportId":1,"openid":"oNtG766MqB_Kax3gx0fIC3b3kcdQ","type":"MIN","insuranceAmountStr":"0.01","orderAmountStr":"0.02","payType":1,"orderRemark":"","productType":"GAME","orderNo":15}
	  creatOrder(params).then(res => {
	    if(res.code == 200){
		  // 起调支付
		  wechatPayment(res.data.payJSON).then((_res:any) =>{
			// 支付后检查是否支付
			  msg('支付成功')
              const time = setTimeout(() => {
			    uni.redirectTo({url:`/pageSignUp/orderMatchSign/orderMatchSign`})
              },500)
		  }).catch((err:any) => {
			msg('支付失败，请重试',false)
		  })
	    }
	})
  }
  
    
		  
  const informationChange = (e:any) => {
    if(e.type == 'cityId'){
      confirmCounty.value = `${e.idList[0].text}/${e.idList[1].text}/${e.idList[2].text}`
      if(e.idList[0]){
        signFrom.value.provinceCode = e.idList[0].value
        signFrom.value.provinceName = e.idList[0].text
      }
      if(e.idList[1]){
        signFrom.value.cityCode = e.idList[1].value
        signFrom.value.cityName = e.idList[1].text
      }
      if(e.idList[2]){
        signFrom.value.districtCode = e.idList[2].value
        signFrom.value.districtName = e.idList[2].text
      }
    } else if (e.type == 'teamName1' && signFrom.value.teamName1) {
		signFrom.value.teamName = ''
	} else if (e.type == 'insCode') {
		signFrom.value.insCode = e.value
		signFrom.value.insName = e.text
	}
  }

  const getAge = (str:string) => {
    if(!str){
      return str
    }
    const toStr = str.toString()
    const yearStr = toStr.substring(6, 10)
    const dateStr = `${toStr.substring(10, 12)}-${toStr.substring(12, 14)}`
    const birthday = `${yearStr}-${dateStr}`
    const birth = new Date(birthday)
    const today = new Date()
    let age = today.getFullYear() - birth.getFullYear()
    if (
      today.getMonth() < birth.getMonth() ||
      (today.getMonth() == birth.getMonth() && today.getDate() < birth.getDate())
    ) {
      age--
    }
    return  age
  }

  // 查看报名须知
  const registrationNotice = () => {
    uni.navigateTo({
      url:`/pageSignUp/personalSignUp/registrationMatchNotice`
    })
  }
  const agreeNotice = () => {
    agreeToExplain.value = true
  }

  const changeTwoFun = (e:any,ids:any[]) => {
    if(ids.length >= 2 && !e.active){
      msg('该项目只能选择两项参加')
      return false
    }
    if(!signFrom.value.idCard){
      msg('请先填写身份证')
      return false
    }else{
      const age = getAge(signFrom.value.idCard)
      if(age > e.maxAge || age < e.minAge){
        msg(`您的年龄不符合，${e.title}报名年龄在${e.minAge}岁~${e.maxAge}岁之间`)
        return false
      }
      return true
    }
  }

  const projectChange = (data:any) => {
    getEventsItemTree({eventId:data}).then(res => {
      if(res.code == 200){
        columnsList.value = res.data
      }else{
        columnsList.value = []
      }
    }).catch(err => {
      columnsList.value = []
    })
  }
  const confirmFromShow = ref(false)
  const confirmFromTime = ref(5)
  const confirmFromTimer = ref(null)
  const confirmCounty = ref('')
  const setConfirmFromTime = () => {
    confirmFromTime.value = 5
    if(confirmFromTimer.value){
      clearInterval(confirmFromTimer.value)
      confirmFromTimer.value = null
    }
    confirmFromTimer.value = setInterval(() => {
      confirmFromTime.value--
      if (confirmFromTime.value === 0){
        clearInterval(confirmFromTimer.value)
        confirmFromTimer.value = null
      }
    }, 1000)
  }

  defineExpose({agreeNotice})
</script>

<template>
  <view class="sign-up">
    <xx-title title="报名赛事"/>
    <!-- <up-notice-bar :duration="5000" text="温馨提示：请完整、准确填写学员相关信息，此信息后期会用于学员分班、训练装备购买等相关事项，请认真填写！" fontSize="12" bgColor="#F56C6C" color="#ffffff"></up-notice-bar> -->
    <view class="sign-body">
      <view class="sign-item">
        <view class="sign-label required">报名项目</view>
        <view class="sign-value">
          {{ eventName }}
        </view>
      </view>
      <!-- <view class="sign-item">
        <view class="sign-label required">报名期数</view>
        <view class="sign-value">
          {{ eventsNumberNameSelect }}
        </view>
      </view> -->


     <!-- <view class="sign-item" v-if="columnsList.length > 0">
        <view class="sign-label required">项目类型</view>
        <view class="sign-value">
          <xx-check v-model="signFrom.eventsItemIds" :disabled="true" :selectValue="signFrom.eventsItemIds" :changeTwoFun="changeTwoFun" label-name="title" value-name="id" :columns="columnsList"/>
        </view>
      </view> -->
    </view>

    <information :info="signFrom" :mechanism="isMechanism" @change="informationChange"/>
  </view>
  <view class="bottom-fixed" :style="{paddingBottom:`calc(${bottomPadding}px + 14rpx)`}">
    <view class="seizeASeat"></view>
  </view>
  <view class="bottom-btn" :style="{paddingBottom:`calc(${bottomPadding}px + 14rpx)`}">
    <view class="personal-tak-care">
      <!-- <view @click.capture.stop="agreeChange"> -->
      <view>
        <up-checkbox :checked="agreeToExplain" @change="agreeChange"></up-checkbox>
      </view>
      我已阅读<text @click="registrationNotice">《报名须知》</text>并知晓同意
    </view>
    <view class="btn">
      <!-- <view class="personal-registration hollowedOut" @click="personalClick(0)" style="width:150rpx;margin-right: 20rpx">保存</view> -->
      <!-- <view class="personal-registration" @click="personalClick(1)" :class="{disabled:!agreeToExplain}">提交</view> -->
      <view class="personal-registration" :class="{disabled:!agreeToExplain}" @click="personalClick()">提交</view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.popup{
  width: calc(100vw - 96rpx);
  height: 75vh;
  display: flex;
  flex-direction: column;
  .popup-head{
    border-bottom: 1px solid #F1F2F4;
    height: 100rpx;
    line-height: 100rpx;
    font-size: 32rpx;
    padding: 0 24rpx;
  }
  .popup-body{
    flex: 1;
    padding: 24rpx 28rpx;
    overflow: hidden;
    .form-body{
      font-size: 28rpx;
      height: 100%;
      overflow: scroll;
      &::-webkit-scrollbar{
        display: none;
      }
      .form-body-item{
        display: flex;
        justify-content: space-between;
        padding: 6rpx 0;
        .label{
          width: 160rpx;
          font-size: 28rpx;
          color: #818496;
          white-space: nowrap;
        }
        .value{
          max-width: calc(100% - 160rpx);
          font-size: 28rpx;
          color: #818496;
          text-align: right;
        }
      }
    }
  }
  .popup-foot{
    border-top: 1px solid #F1F2F4;
    display: flex;
    gap: 20rpx;
    padding: 20rpx 28rpx;
  }
}
.sign-up{
  width: 100%;
  min-height: 100vh;
  padding-top: 1rpx;
  background-color: #F5F5F5;
}
.bottom-fixed{
  padding-top: 14px;
  .seizeASeat{
    height: 138rpx;
  }
}
.sign-body{
  margin: 32rpx;
  background-color: #FFFFFF;
  border-radius: 16rpx;
  padding: 0 32rpx;
  .sign-item{
    padding: 24rpx 0;
    display: flex;
    align-items: flex-start;
    border-bottom: 1px solid #F5F5F5;
    &:last-child{
      border-bottom: none;
    }
    .sign-label{
      color: #505363;
      font-size: 28rpx;
      width: 160rpx;
      &.required{
        position: relative;
        padding-left: 20rpx;
        &:before{
          content: '*';
          display: block;
          position: absolute;
          color: #ff3c3c;
          top: 0;
          left: 0;
        }
      }
    }
    .sign-value{
      width: calc(100% - 160rpx);
      font-size: 28rpx;
      color: #21252E;
      font-weight: 500;
      input{
        width: 100%;
        font-weight: 500;
      }
      textarea{
        background-color: #F5F5F5;
        border-radius: 12rpx;
        box-sizing: border-box;
        font-weight: 500;
        width: 100%;
        padding:10rpx;
        height: 150rpx;
      }
    }
  }
}
.bottom-btn{
  position: fixed;
  bottom: 0;
  width: 100%;
  padding-left: 28rpx;
  padding-right: 28rpx;
  box-sizing: border-box;
  border-top: 1px solid #F1F2F4;
  padding-top: 14rpx;
  z-index: 10;
  background-color: #FFFFFF;
  .btn{
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .personal-tak-care{
    display: flex;
    align-items: center;
    font-size: 28rpx;
    color: #505363;
    margin-bottom: 10rpx;
    text{
      color: #1677FE;
    }
  }
  .personal-registration{
    background: #92C75B;
    color: #FFFFFF;
    border-radius: 16rpx;
    width:calc(100% - 20rpx);
    border:1rpx solid #92C75B;
    padding: 16rpx 0;
    letter-spacing: 2rpx;
    font-weight: 500;
    text-align: center;
    &.disabled{
      background-color: #E5E5E5;
      color:#818496;
      border:1rpx solid #E5E5E5;
    }
    &.hollowedOut{
      border:1rpx solid #92C75B;
      color: #92C75B;
      background-color: transparent;
    }
  }
}
</style>
